package com.mumulx.check.web.config.security.auth;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mumulx.check.service.util.RespBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
@Slf4j
public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Value("${spring.security.loginType}")
    private String loginType;

    private static ObjectMapper objectMapper = new ObjectMapper();

    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception)
            throws IOException, ServletException {

        String errorMsg = "密码输入错误!";
        response.setContentType("application/json;charset=UTF-8");
        if(loginType.equalsIgnoreCase("JSON")){

            if(exception instanceof UsernameNotFoundException){
                errorMsg = "用户名不存在，请检查用户名！";
            }else if (exception instanceof DisabledException){
                errorMsg = "该账号不可用，请联系管理员！";
            } else if (exception instanceof SessionAuthenticationException) {
                errorMsg = "该账号已在其他地方登录，如果不是本人登录请联系管理员！!!";
            }else if (exception instanceof AccountExpiredException) {
                errorMsg="账户过期，请联系管理员!";
            }else if (exception instanceof CredentialsExpiredException) {
                errorMsg="密码输入错误!";
            }else if (exception instanceof LockedException) {
                errorMsg="账户被锁定，请联系管理员!";
            }else if (exception instanceof BadCredentialsException) {
                errorMsg="用户名或者密码输入错误，请重新输入!";
            }
            PrintWriter out = response.getWriter();
            out.write(objectMapper.writeValueAsString(
                    RespBean.error(errorMsg)
            ));
            out.flush();
            out.close();
            log.error("用户登录失败"+exception.getMessage());
            exception.printStackTrace();
        }else{
            //跳转到登陆页面
            super.onAuthenticationFailure(request,response,exception);
        }

    }
}
